package com.flying.flyingchessgame.exception;

import com.flying.flyingchessgame.dto.response.MessageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import javax.validation.ConstraintViolationException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * <p>
 * 处理应用程序中的各种异常，提供统一的错误响应格式。
 * 使用@ControllerAdvice注解，对所有控制器抛出的异常进行处理。
 * </p>
 * 
 * @author flying-chess
 * @version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理用户未找到异常
     * <p>
     * 处理用户不存在时抛出的异常。
     * </p>
     *
     * @param ex 用户未找到异常
     * @param request Web请求
     * @return 包含错误信息的响应
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<?> handleUsernameNotFoundException(UsernameNotFoundException ex, WebRequest request) {
        logger.error("用户未找到异常: {}", ex.getMessage());
        MessageResponse errorResponse = new MessageResponse("错误: " + ex.getMessage());
        errorResponse.setCode(404);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
    }

    /**
     * 处理认证凭证错误异常
     * <p>
     * 处理用户名或密码错误时抛出的异常。
     * </p>
     *
     * @param ex 认证凭证异常
     * @param request Web请求
     * @return 包含错误信息的响应
     */
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<?> handleBadCredentialsException(BadCredentialsException ex, WebRequest request) {
        logger.error("凭证错误异常: {}", ex.getMessage());
        MessageResponse errorResponse = new MessageResponse("错误: 用户名或密码不正确");
        errorResponse.setCode(401);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
    }

    /**
     * 处理参数验证失败异常
     * <p>
     * 处理@Valid注解验证失败时抛出的异常，返回详细的字段错误信息。
     * </p>
     *
     * @param ex 方法参数验证异常
     * @return 包含错误详情的响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        logger.warn("参数验证失败: {}", errors);
        return ResponseEntity.badRequest().body(errors);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException ex) {
        logger.error("约束违反异常: {}", ex.getMessage());
        MessageResponse errorResponse = new MessageResponse("错误: " + ex.getMessage());
        errorResponse.setCode(400);
        return ResponseEntity.badRequest().body(errorResponse);
    }

    /**
     * 处理通用异常
     * <p>
     * 处理所有其他未被特定处理器捕获的异常。
     * </p>
     *
     * @param ex 异常
     * @param request Web请求
     * @return 包含错误信息的响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
        logger.error("全局异常: ", ex);
        MessageResponse errorResponse = new MessageResponse("服务器内部错误，请稍后再试");
        errorResponse.setCode(500);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
    }
} 